﻿namespace Pub.Class
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.CompilerServices;
    using System.Threading;

    public class ThreadEx
    {
        private List<AutoResetEvent> handlerStack = new List<AutoResetEvent>();

        public static void InParallel(params ThreadStart[] tasks)
        {
            new List<ThreadStart>(tasks).InParallel();
        }

        public static void InParallel(int maxThreads, params ThreadStart[] tasks)
        {
            new List<ThreadStart>(tasks).InParallel(maxThreads);
        }

        public void QueueWorkItem(WaitCallback callBack, object userstate)
        {
            WorkItemInfo state = new WorkItemInfo {
                AutoResetEvent = new AutoResetEvent(false)
            };
            this.handlerStack.Add(state.AutoResetEvent);
            state.WaitCallback = callBack;
            state.UserState = userstate;
            ThreadPool.QueueUserWorkItem(delegate(Object state1)
            {
                WorkItemInfo info = (WorkItemInfo) state1;
                try
                {
                    info.WaitCallback(info.UserState);
                }
                finally
                {
                    info.AutoResetEvent.Set();
                }
            }, state);
        }

        public void WaitAllComplete()
        {
            foreach (AutoResetEvent event2 in this.handlerStack)
            {
                event2.WaitOne();
            }
        }

        private class WorkItemInfo
        {
            public System.Threading.AutoResetEvent AutoResetEvent { get; set; }

            public object UserState { get; set; }

            public System.Threading.WaitCallback WaitCallback { get; set; }
        }
    }
}

